<?php
/** [文档表逻辑层模型]
 * @Author: 976123967@qq.com
 * @Date:   2015-01-15 10:50:57
 * @Last Modified by:   happy
 * @Last Modified time: 2015-03-14 17:36:32
 */
class ArticleLogic extends Model{

	// 表名称
	protected $tableName = 'article';


	// 自动验证
	public $_validate = array(
		array('category_cid','/^[^0]\d*$/','请选择栏目',1,'regex',3),  
		array('article_title','require','标题不能为空',1,'regex',3),
		array('sort','require','请输入排序值',0,'regex',3),
		array('sort','/^\d+$/i','排序值只能是数字',0,'regex',3),
		array('click','require','请输入浏览次数',0,'regex',3),
		array('click','/^\d+$/i','浏览次数只能是数字',0,'regex',3),
	);

	// 自动完成
    // array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto = array (
        // 发布时间
        array('addtime','_addtime',3,'callback'),
        // 编辑时间
        array('edittime','time',3,'function'),
        // 属性
        array('flag','_flag',3,'callback'),
        // user_uid
		array('user_uid','_uid',1,'callback'),
    );

    // 发布时间
    public function _addtime($con)
    {
    	if(!$con)
    		return strtotime(date('Y-m-d'));
    	else
    		return strtotime($con);
    }


    // 用户uid
	public function _uid()
	{
		return session('uid');
	}

    // 属性自动完成
	public function _flag()
	{
		$flag = I('post.flag');
		return $flag? implode(',', $flag):'';
	}




	/**
	 * [set_flag 设置属性对应关系]
	 */
	public function set_flag()
	{
		$key = I('post.key');
		$data = array();
		foreach ($key as $k => $v)
		{
			$data['flag'][$v] = $k;
		}
		return file_put_contents('Data/Config/flag.inc.php', "<?php \nreturn ".var_export($data,true)."; \n?>");
	}

	/**
	 * [check_cid 查找当前cid是否有文章]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function check_cid($cid)
	{
		$data = $this->where(array('category_cid'=>$cid))->find();
		if(!$data)
			return false;
		else
			return $data;
	}

	
	/**
	 * [find_one 查找一条记录]
	 * @return [type] [description]
	 */
	public function find_one()
	{
		$aid  		 = I('get.aid');
		$cid  		 = I('get.cid');
		
		/***表名称***/ 
		$categoryAll = S('category');
		$mid		 = $categoryAll[$cid]['model_mid'];
		$table 		 = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');
		$data        = D('ArticleView')->find_one_by_aid(array('aid'=>$aid,'table'=>$table));
		if(!$data)
		{
			$this->error = '信息文档不存在';
			return false;
		}
		// 格式化数据
		$data['time'] 	  = $data['addtime'];
		$data['addtime']  = date('Y-m-d',$data['addtime']);

		// 是否有图片
		$data['has_pic']  = $data['pic']?true:false;
		// 是否有文件
		$data['has_file'] = $data['file']?true:false;

		// 图片路径
		$data['pic']      = $data['pic']?__ROOT__.'/'.$data['pic']:'';
		// 文件路径
		$data['file']     = $data['file']?__ROOT__.'/'.$data['file']:'';

		$data['downurl']   = $data['file']?U('down',array('aid'=>$aid,'show'=>'file')):'';


		return $data;

	}




	/**
	 * [update_article 更新文档]
	 * @return [type] [description]
	 */
	public function update_article()
	{
		if(!$this->create())
			return false;
		$data = $this->data;
		// 上传图片
		$pic  = $this->alter_pic();

		if($pic===false)
			return false;
		if($pic!='')
			$data['pic'] = $pic;

		// 上传文件
		$file  = $this->alter_file();
		if($file===false)
			return false;
		if($file!='')
			$data['file'] = $file;

		$this->save($data);
		
		$aid = I('post.aid');

		// 添加图片集
		D('Pic','Logic')->add_pic($aid);




		// 修改附表字段值
		$this->update_ext($aid);

		// 更新编辑器上传的附件
		D('Upload','Logic')->update_uoload_attachment($aid);

		return true;
	}

	/**
	 * [update_ext 修改附件]
	 * @return [type] [description]
	 */
	public function update_ext($aid)
	{
		$cid = I('post.category_cid');

		/***当前模型所扩展有字段***/ 
		$categoryAll = S('category');
		$mid		 = $categoryAll[$cid]['model_mid'];
		$field       = D('Field','Logic')->get_all_by_model_mid($mid);
		
		
		// 当前模型的表名称
		$table = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');


		$data = array();
		// 关联字段
		$data['article_aid'] = $aid;
		foreach($field as $v)
		{
			// 字段内容值初始化
			$value = '';

			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{
				$dir = $v['show_type']==9?'image':'file';
				$type = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value === false)
					continue;
				if($value == '')
					continue;

			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);
			}
			else
			{
				// stripcslashes 处理引号被转义问题
				$value = stripcslashes($_POST[$v['fname']]);
			}
			// 有内容更新
			
			$data[$v['fname']] = $value;
		}
		
		M($table)->where(array('article_aid'=>$aid))->save($data);

		return true;
	}


	/**
	 * [add_article 添加文档]
	 */
	public function add_article()
	{

		// 主表数据验证
		if(!$this->create())
			return false;
		$data = $this->data;

		// 上传图片
		$pic  = $this->alter_pic();
		if($pic===false)
			return false;
		$data['pic'] = $pic;

		// 上传文件
		$file  = $this->alter_file();
		if($file===false)
			return false;
		$data['file'] = $file;

		// 添加主表信息
		$aid = $this->add($data);

		// 添加图片集
		D('Pic','Logic')->add_pic($aid);

		// 添加附表字段值
		$this->add_ext($aid);

		// 更新编辑器上传的附件
		D('Upload','Logic')->update_uoload_attachment($aid);

		return $aid;
	}


	/**
	 * [add_ext 添加附表字段值]
	 * @param [type] $aid [description]
	 */
	public function add_ext($aid)
	{
		$cid = I('post.category_cid');

		/***当前模型所扩展有字段***/ 
		$categoryAll = S('category');
		$mid		 = $categoryAll[$cid]['model_mid'];
		$field       = D('Field','Logic')->get_all_by_model_mid($mid);
		
		
		// 当前模型的表名称
		$table = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');

		$data = array();
		// 关联字段
		$data['article_aid'] = $aid;
		foreach($field as $v)
		{

			// 字段内容值初始化
			$value = '';


			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{

				$dir   = $v['show_type']==9?'image':'file';
				$type  = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value===false)
					$value = '';
			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);
			}
			else
			{
				// stripcslashes 处理引号被转义问题
				$value = stripcslashes($_POST[$v['fname']]);
			}
			$data[$v['fname']] = $value;
		}
		
		
		
		return M($table)->add($data);
	

	}

	/**
	 * [upload_ext 上传附表中的文件和图片]
	 * @param  [type] $uploadname [description]
	 * @param  [type] $dir        [description]
	 * @param  [type] $type       [description]
	 * @return [type]             [description]
	 */
	public function upload_ext($uploadname,$dir,$type)
	{


		if(!empty($_FILES[$uploadname]['name']))
		{

			// 删除原来的文件
			$aid = I('post.aid');
			if($aid)
			{
				/***表名称***/ 
				$cid = I('post.category_cid');
				$categoryAll = S('category');
				$mid		 = $categoryAll[$cid]['model_mid'];
				$table 		 = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');
				
				$file = D('ArticleView')->get_field_by_aid(array('aid'=>$aid,'table'=>$table,'field'=>$uploadname));
				is_file($file) && unlink($file);
			}




			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', $type);

            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/'.$dir.'/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            //is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES[$uploadname],$savePath))
            {
            	//p($info);die;
            	return $info[0]['savepath'].$info[0]['savename'];
            }
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		return '';
	}





	/**
	 * [alter_pic 上传图片]
	 * @return [type] [description]
	 */
	public function alter_pic()
	{

		$aid = I('post.aid');
		if($aid&&!empty($_FILES['pic']['name']))
		{
			$pic = $this->where(array('aid'=>$aid))->getField('pic');
			is_file($pic) and unlink($pic);
		}

		if(!empty($_FILES['pic']['name']))
		{
			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', C('cfg_image'));
            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/image/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            //is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES['pic'],$savePath))
                return $info[0]['savepath'].$info[0]['savename'];
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		else
			return '';
	}

	/**
	 * [alter_file 上传文件]
	 * @return [type] [description]
	 */
	public function alter_file()
	{

		$aid = I('post.aid');
		if($aid&&!empty($_FILES['file']['name']))
		{
			$file=$this->where(array('aid'=>$aid))->getField('file');
			is_file($file) and unlink($file);
		}

		if(!empty($_FILES['file']['name']))
		{
			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', C('cfg_file'));
            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/file/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            //is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES['file'],$savePath))
                return $info[0]['savepath'].$info[0]['savename'];
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		else
			return '';
	}


	/**
	 * [get_all 读取对应栏目下面的所有的数据]
	 * @return [type] [description]
	 */
	public function get_all()
	{
		// 开始时间
		$beginTime  	= I('get.search_begin_time','');  
		// 结束时间
		$endTime    	= I('get.search_end_time','');
		// 搜索类型
		$searchType 	= I('get.search_type',0,'intval');
		// 文档属性
		$flag       	= I('get.flag','');
		// 关键词
		$searchKeyword  = I('get.search_keyword','');
		// 审核状态
		$state 			= I('get.state',0,'intval');



		// 更具初始化数据设置GET
		if(!$beginTime)
			$_GET['search_begin_time'] = '';
		if(!$endTime)
			$_GET['search_end_time'] = '';
		if(!$searchType)
			$_GET['search_type'] = 1;
		if(!$flag)
			$_GET['flag'] = '';
		if(!$searchKeyword)
			$_GET['search_keyword'] = '';	
		if(!$state)
			$_GET['state'] = 2;	

		//p($_GET);

		// 设置where
		$where  = null;

		// 开始时间
		if($beginTime)
			$where[]  = 'addtime >='. strtotime($beginTime);
		// 结束时间
		if($endTime)
			$where[]  = 'addtime <='.strtotime($endTime)+24*60*60;
		// 文档属性
		if($flag)
			$where[] = "find_in_set('{$flag}',flag)";
		// 搜索关键词
		if($searchKeyword && $searchType)
		{
			switch ($searchType) {
				case 1: //标题
					$where[] = "article_title like '%{$searchKeyword}%'";
					break;
				case 2: //描述
					$where[] = "description like '%{$searchKeyword}%'";
					break;
				case 3: //用户名
					$where[] = "username like '%{$searchKeyword}%'";
					break;
			}
			
		}

		// 审核状态
		switch ($_GET['state']) 
		{
			case 1:
				$where['verifystate']   = 1;
				break;
			case 2:
				$where['verifystate']   = 2;
				break;
		}

		// 分类ID
		$cid = I('get.cid');
		$childCids = D('Category')->get_child_cid($cid);
		$where['category_cid'] = array('in',$childCids);

		$articleViewModel = D('ArticleView');

		
		$count = $articleViewModel->where($where)->count();
	
		// 没有数据
		if(!$count)
			return false;
		// 分页
		import('ORG.Util.Page');// 导入分页类
		$page  = new Page($count,20);
		
		$field ='sort,verifystate,aid,category_cid,article_title,keywords,description,username,cname,remark,edittime,addtime,pic,content,file,flag';
		
		// 排序
		$order = 'article.sort asc ,aid desc';
		// limit
		$limit = $page->firstRow.','.$page->listRows;
		// 读取数据
		$data  = $articleViewModel->where($where)->limit($limit)->order($order)->field($field)->select();

		$category = S('category');

		// 处理数据
		foreach ($data as $k=>$v)
		{

			$data[$k]['verifystate'] = $v['verifystate']==1?'审核中':($v['verifystate']==2?'审核通过':'审核失败');
			// 编辑时间
			$data[$k]['edittime']    = date('Y-m-d',$v['edittime']);
			// 发布时间
			$data[$k]['time']        = $v['addtime'];
			$data[$k]['addtime']     = date('Y-m-d',$v['addtime']);

			// 控制器
			$remark 			 = strtolower($v['remark']);
			// 当前URL地址
			$data[$k]['url']     =U('/'.$remark.'_v_'.$v['category_cid'].'_'.$v['aid']);
			
		}
		// 分页样式更改
		$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% 页 </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');

		// 页脚信息
		$data['page'] = $page->show();


		return $data;

	}

	/**
	 * [operation 批量操作]
	 * @return [type] [description]
	 */
	public function operation()
	{
		$aid  = I('post.aid');
		switch (true) 
		{
			// 排序
			case isset($_POST['update_sort']): 
				$sort = I('post.sort');
				foreach($aid as $k=>$v)
				{
					$this->save(array('sort'=>$sort[$k],'aid'=>$v));
				}
				$msg= '文档排序成功';
				break;

			
			// 删除
			case isset($_POST['update_del']):
				foreach($aid as $k=>$v)
				{
					$cid = $this->where(array('aid'=>$v))->getField('category_cid');
					$this->del_article_by_aid_cid($v,$cid);	
				}
				$msg= '文档删除成功';
			break;

			// 取消审核
			case isset($_POST['update_cancle_state']):
				foreach($aid as $k=>$v)
				{
					$this->save(array('verifystate'=>1,'aid'=>$v));	
				}
				$msg= '文档取消审核成功';
				break;
	
			// 审核通过
			case isset($_POST['update_check_state']):
				foreach($aid as $k=>$v)
				{
					$this->save(array('verifystate'=>2,'aid'=>$v));
				}
				$msg= '文档审核成功';
				break;


			// 审核操作属性
			case isset($_POST['update_check_operation']):
				$flag = I('post.opa');
				foreach($aid as $k=>$v)
				{
					// 把原先的属性取出
					$oldFlag = $this->where(array('aid'=>$v))->getField('flag');
					// 验证是否已经有属性存在
					if(!strchr($oldFlag,$flag))
						$oldFlag .=','.$flag;
					$newFlag = trim($oldFlag,',');
					$this->save(array('flag'=>$newFlag,'aid'=>$v));
				}
				$msg= '文档设置属性成功';
				break;


			// 取消操作属性
			case isset($_POST['update_cancle_operation']):
				$flag = I('post.opa');
				foreach($aid as $k=>$v)
				{

					// 把原先的属性取出
					$oldFlag = $this->where(array('aid'=>$v))->getField('flag');
					// 验证是否已经有属性存在
					if(strchr($oldFlag,$flag))
					{
						$oldFlag  = preg_replace('/(,)?'.$flag.'(,)?/', ',', $oldFlag);
					}
					$newFlag = trim($oldFlag,',');

					header("Content-type:text/html;charset=utf-8");
					
					$msg= '文档取消属性成功';
					$this->save(array('flag'=>$newFlag,'aid'=>$v));
				}
			break;

			default:
				$this->error = '操作选择错误';
				return false;
		}

		return $msg;

	}


	/**
	 * [del_attachment 删除附件]
	 * @return [type] [description]
	 */
	public function del_attachment()
	{
		$aid        = I('get.aid');
		$field      = I('get.field');
		$cid        = $this->where(array('aid'=>$aid))->getField('category_cid');
		$category   = S('category');
		$mid        = $category[$cid]['model_mid'];
		$modelfield = D('Field','Logic')->get_all_field_name_by_model_mid($mid);
		

		/***表名称***/ 
		$categoryAll = S('category');
		$mid		 = $categoryAll[$cid]['model_mid'];
		$table 		 = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');
		$data        = D('ArticleView')->get_field_by_aid(array('aid'=>$aid,'table'=>$table,'field'=>$field));
	
		if(!$data)
		{
			$this->error = '链接错误';
			return false;
		}

		is_file($data) && unlink($data);

		if(in_array($field, $modelfield))
			M($table)->where(array('article_aid'=>$aid))->save(array($field=>''));
		else
			$this->where(array('aid'=>$aid))->save(array($field=>''));
		
		
		return true;
	}

	/**
	 * [del_article 删除文档接收数据$aid,$cid]
	 * @return [type] [description]
	 */
	public function del_article()
	{
		$aid      = I('get.aid');
		$cid      = I('get.cid');
		$this->del_article_by_aid_cid($aid,$cid);
		return true;
	}
	/**
	 * [del_article_by_aid_cid 删除文档通过$aid,$cid]
	 * @param  [type] $aid [description]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function del_article_by_aid_cid($aid,$cid)
	{
		$category = S('category');
		$mid      = $category[$cid]['model_mid'];
		$table 	  = 'article_'.D('Model')->where(array('mid'=>$mid))->getField('name');
	
		

		// 附件字段
		$attachmentField = D('Field','Logic')->get_all_attachment_field_name_by_model_mid($mid);
		
		// 遍历字段 删除文件
		if($attachmentField)
		{
			foreach ($attachmentField as $v) 
			{
				$file = D('ArticleView')->get_field_by_aid(array('aid'=>$aid,'table'=>$table,'field'=>$v));
				is_file($file) && unlink($file);
			}
		}

		//删除附表数据
		M($table)->where(array('article_aid'=>$aid))->delete();

		//删除图集
		D('Pic','Logic')->delete_pic_by_article_aid($aid);

		// 删除附件表数据
		D('Upload','Logic')->delete_upload_by_article_aid($aid);


		//删除主表数据
		$pic  = $this->where(array('aid'=>$aid))->getField('pic');
		$file = $this->where(array('aid'=>$aid))->getField('file');
		is_file($pic)  && unlink($pic);
		is_file($file) && unlink($file);
		$this->delete($aid);
	}


}